package com.etc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.etc.entity.Equipment;
import com.etc.entity.EquipmentArmor;
import com.etc.entity.EquipmentFactory;
import com.etc.entity.EquipmentWeapon;
import com.etc.tools.DBTools;

public class EquipmentDAO {

	DBTools tool = new DBTools();
	Connection conn = tool.getConnection();
	
	//添加装备
	public void addEquipment(Equipment equip) {
		String sql = "insert into T_ITEM_EQUIPMENT values(?,?,?,?,?,?,?,?,?)";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, equip.getEquipId());
			ps.setString(2, equip.getEquipName());
			ps.setInt(3, equip.getAttrHeal());
			ps.setInt(4, equip.getAttrImage());
			ps.setInt(5, equip.getAttrAttack());
			ps.setInt(6, equip.getAttrCrit());
			ps.setInt(7, equip.getAttrDefense());
			ps.setInt(8, equip.getAttrSpeed());
			ps.setString(9, equip.getType());
			int confirm = ps.executeUpdate();
			if(confirm == 1) {
				System.out.println("装备添加成功");
			}
		} catch (SQLException e) {
			System.out.println("装备添加异常");
			e.printStackTrace();
		}
		
	}
	//根据id查找装备
	public Equipment findEquipById(String equipId) {
		String sql = "select * from t_item_equipment where equip_id = ?";
		Equipment equipment = null;
		String classType;
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, equipId);
			ResultSet set = ps.executeQuery();
			set.next();
			if(set.getString("type").equals("主手武器")) {
				classType = "EquipmentWeapon";
			}else {
				classType = "EquipmentArmor";
			}
			equipment = EquipmentFactory.createEquipment(classType, set.getString("equip_id"),
					set.getString("equip_name"), set.getInt("attr_heal"), set.getInt("attr_image"),
					set.getInt("attr_attack"), set.getInt("attr_critical"), 
					set.getInt("attr_defense"), set.getInt("attr_speed"), 
					set.getString("type"));
		} catch (SQLException e) {
			System.out.println("装备查找异常");
			e.printStackTrace();
		}
		return equipment;
	}
	
	public ArrayList<Equipment> findEquipByType(String type) {
		String sql = "select * from t_item_equipment where type = ?";
		ArrayList<Equipment> equipments = new ArrayList<>();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, type);
			ResultSet set = ps.executeQuery();
			while(set.next()) {
				Equipment equipment = findEquipById(set.getString("equip_id"));
				equipments.add(equipment);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return equipments;
	}
	//
}
